<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="packageRegister"
    @ok="confirmSubmit"
    @close="drawerReset"
    showFooter
    :closable="false"
    isDetail
  >
    <div class="drawer-package">
      <div class="package-form" v-show="drawerInfo.type !== operateActionType.VIEW">
        <a-form
          ref="formRef"
          :colon="false"
          autocomplete="off"
          :label-col="{ style: { width: '90px' } }"
          :model="formState"
          :rules="getFormRules"
          lableWidth
        >
          <div class="package-box">
            <div class="global-drawer-title">套餐基本信息</div>
            <div class="box-form">
              <a-form-item label="套餐状态" name="packageStatus">
                <a-switch
                  v-model:checked="formState.packageStatus"
                  :checkedValue="1"
                  :unCheckedValue="2"
                  checked-children="已上架"
                  un-checked-children="已下架"
                />
              </a-form-item>
              <a-form-item label="套餐名称" name="packageName">
                <a-input
                  allowClear
                  :maxLength="20"
                  placeholder="请输入套餐名称"
                  v-model:value.trim="formState.packageName"
                >
                </a-input>
              </a-form-item>
              <a-form-item label="套餐介绍" name="packageDesc">
                <a-textarea
                  allowClear
                  :maxLength="100"
                  :autoSize="{ minRows: 3, maxRows: 3 }"
                  placeholder="请输入套餐介绍"
                  v-model:value.trim="formState.packageDesc"
                >
                </a-textarea>
              </a-form-item>
            </div>
            <div class="box-detail">
              <a-form-item label="套餐主图" name="packageIconKey">
                <UploadFile v-model="formState.packageIconKey" />
                <div class="upload-info">
                  <info-circle-outlined class="info-icon" />
                  只支持jpg、png格式，750px*240px，不超过10M
                </div>
              </a-form-item>
            </div>

            <div class="box-detail">
              <a-form-item label="套餐详情" name="packageDetail">
                <div class="detail-content">
                  <WangeditorEditor :key="detailKey" v-model="formState.packageDetail" />
                </div>
              </a-form-item>
            </div>
          </div>
          <div class="package-box">
            <div class="global-drawer-title">套餐收费信息</div>
            <div class="box-form">
              <a-form-item label="缴费方式" name="paymentMethod">
                <a-radio-group v-model:value="formState.paymentMethod" @change="paymentMethodChange">
                  <a-radio :value="1">在线支付</a-radio>
                  <a-radio :value="2">联系客服</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item label="套餐类型" name="packageType">
                <a-radio-group
                  v-model:value="formState.packageType"
                  :disabled="drawerInfo.type === operateActionType.EDIT"
                  @change="paymentMethodChange"
                >
                  <a-radio :value="1">功能收费</a-radio>
                  <a-radio :value="2">数量收费</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item label="费用" name="unitPrice" class="unit-price">
                <a-input
                  allowClear
                  :suffix="formState.packageType === 2 ? '元' : '元/税号'"
                  :maxLength="7"
                  placeholder="请输入费用"
                  @input="formState.unitPrice = formState.unitPrice.replace(/[^\d]/g, '')"
                  v-model:value.trim="formState.unitPrice"
                >
                </a-input>
                <a-input
                  v-show="formState.packageType === 2"
                  allowClear
                  :maxLength="10"
                  placeholder="数量"
                  @input="formState.unitQuantity = formState.unitQuantity.replace(/[^\d]/g, '')"
                  v-model:value.trim="formState.unitQuantity"
                  class="unit-num"
                >
                </a-input>
                <a-select
                  v-show="formState.packageType === 2"
                  v-model:value="formState.unit"
                  placeholder="请选择单位"
                  :options="unitOpts"
                ></a-select>
              </a-form-item>
              <a-form-item label="服务时间" name="serviceDays">
                <a-input
                  allowClear
                  suffix="天"
                  :maxLength="3"
                  @input="formState.serviceDays = formState.serviceDays.replace(/[^\d]/g, '')"
                  placeholder="请输入服务时间"
                  v-model:value.trim="formState.serviceDays"
                >
                </a-input>
              </a-form-item>
              <a-form-item label="是否支持试用" name="tryDays" v-show="formState.packageType == 1">
                <div class="form-flex">
                  <a-form-item-rest>
                    <a-select
                      v-model:value="supportTrial"
                      placeholder="请选择"
                      style="width: 198px"
                      @change="() => (formState.tryDays = '')"
                    >
                      <a-select-option value="1"> 否 </a-select-option>
                      <a-select-option value="2"> 是 </a-select-option>
                    </a-select>
                  </a-form-item-rest>

                  <a-input
                    allowClear
                    suffix="天"
                    :maxLength="3"
                    :disabled="supportTrial == '1'"
                    style="margin-left: 8px; width: 198px"
                    placeholder="请输入试用天数"
                    @input="formState.tryDays = formState.tryDays.replace(/[^\d]/g, '')"
                    v-model:value.trim="formState.tryDays"
                  >
                  </a-input>
                </div>
              </a-form-item>
              <a-form-item>
                <template #label>
                  <div class="require-icon-color"></div>
                  商品配置
                </template>
                <div class="form-configuration">
                  <div class="configuration-orgin">
                    <div class="box-header">
                      <div class="header-num">
                        <a-checkbox
                          v-model:checked="checkAll"
                          :indeterminate="checkIndeterminate"
                          :disabled="
                            drawerInfo.allGoodsList.length === 0 ||
                            drawerInfo.allGoodsList.length === drawerInfo.originSelectList.length
                          "
                          @change="onCheckAllChange"
                        >
                        </a-checkbox>
                        <div class="num-total">
                          {{ drawerInfo.selectGoodsList.length }}/{{ drawerInfo.allGoodsList.length }}条
                        </div>
                      </div>
                      <div class="header-txt">源列表</div>
                    </div>
                    <div class="box-list">
                      <a-checkbox-group v-model:value="drawerInfo.selectGoodsList" @change="onCheckChange">
                        <div class="list-item" v-for="item in drawerInfo.allGoodsList" :key="item.goodsCode">
                          <a-checkbox :disabled="authDisabled(item.goodsCode)" :value="item.goodsCode">{{
                            item.goodsName
                          }}</a-checkbox>
                        </div>
                      </a-checkbox-group>
                      <div class="list-empty" v-if="drawerInfo.allGoodsList.length === 0">暂无数据</div>
                    </div>
                  </div>
                  <div class="configuration-select">
                    <div class="box-header">
                      <div class="header-num">{{ drawerInfo.selectGoodsList.length }}条</div>
                      <div class="header-txt">已选</div>
                    </div>
                    <div class="box-list">
                      <div class="list-item" v-for="item in drawerInfo.selectGoodsList" :key="item">
                        <div class="item-name">{{ getShowName(item) }}</div>
                        <close-circle-filled
                          v-if="!authDisabled(item)"
                          class="item-close"
                          @click="removeSelect(item)"
                        />
                      </div>
                      <div class="list-empty" v-if="drawerInfo.selectGoodsList.length === 0">暂无数据</div>
                    </div>
                  </div>
                </div>
              </a-form-item>
            </div>
          </div>
        </a-form>
      </div>
      <div class="package-view" v-show="drawerInfo.type === operateActionType.VIEW">
        <div class="package-box">
          <div class="global-drawer-title">{{ drawerInfo.record.packageName }}</div>
          <div class="box-desc">
            <a-descriptions layout="vertical" :colon="false">
              <a-descriptions-item label="最近一次操作人">{{ drawerInfo.record.updateByUserName }}</a-descriptions-item>
              <a-descriptions-item label="操作时间">{{ drawerInfo.record.updateTime }}</a-descriptions-item>
              <a-descriptions-item label="创建时间">{{ drawerInfo.record.createTime }}</a-descriptions-item>
            </a-descriptions>
          </div>
        </div>
        <div class="package-box">
          <div class="global-drawer-title">套餐详情</div>
          <div class="box-desc">
            <a-descriptions layout="vertical" :colon="false">
              <a-descriptions-item label="套餐名称">{{ drawerInfo.record.packageName }}</a-descriptions-item>
              <a-descriptions-item label="套餐描述">{{ drawerInfo.record.packageDesc }}</a-descriptions-item>
              <a-descriptions-item label="商品配置">{{ drawerInfo.record.goodsNameSetValue }}</a-descriptions-item>
              <a-descriptions-item label="缴费方式">
                <span v-if="drawerInfo.record.paymentMethod == 1">在线支付</span>
                <span v-else-if="drawerInfo.record.paymentMethod == 2">联系客服</span>
              </a-descriptions-item>
              <a-descriptions-item label="套餐类型">
                <span v-if="drawerInfo.record.packageType == 1">功能收费</span>
                <span v-else-if="drawerInfo.record.packageType == 2">数量收费</span>
              </a-descriptions-item>
              <a-descriptions-item label="费用"
                >{{ drawerInfo.record.unitPrice
                }}{{
                  drawerInfo.record.packageType === 2
                    ? `元/${drawerInfo.record.unitQuantity == 1 ? '' : drawerInfo.record.unitQuantity}${
                        drawerInfo.record.unit || '个'
                      }`
                    : '元/税号'
                }}
              </a-descriptions-item>
              <a-descriptions-item label="服务时间">{{ drawerInfo.record.serviceDays }}天</a-descriptions-item>
              <a-descriptions-item label="套餐状态">
                <span class="global-active-status" v-if="drawerInfo.record.packageStatus == '1'">已上架</span>
                <span class="global-stop-status" v-else-if="drawerInfo.record.packageStatus == '2'">已下架</span>
              </a-descriptions-item>
            </a-descriptions>
          </div>
        </div>
      </div>
    </div>
    <template #centerFooter>
      <a-button type="primary" @click="previewData"> 预览 </a-button>
    </template>
    <PackagePreview @register="packagePreviewRegister" />
  </BasicDrawer>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, unref } from 'vue'
import { BasicDrawer, useDrawerInner, useDrawer } from '@/components/Drawer'
import Empty from '@/components/Empty/index.vue'
import WangeditorEditor from '@/components/WangeditorEditor/index.vue'
import UploadFile from '@/components/UploadFile/index.vue'
import { operateActionType } from '@/types/enum'
import { getUpdateSchemaArr } from '@/utils/formSchema'
import PackagePreview from './packagePreview.vue'
import { numTransString, scrollToFirstError } from '@/utils'
import { message } from 'ant-design-vue'
import { InfoCircleOutlined, CloseCircleFilled } from '@ant-design/icons-vue'
import { cloneDeep } from 'lodash-es'
import api from '@/api'

const { allGoods, packageAdd, packageEdit, packageDetail } = api

const emit = defineEmits(['operateSuccess', 'register'])

const [packagePreviewRegister, { openDrawer: PackagePreviewDrawer }] = useDrawer()

const drawerInfo = reactive<any>({
  type: '',
  record: {},
  allGoodsList: [],
  selectGoodsList: [],
  originSelectList: []
})

const detailKey = ref(0)
const unitOpts = [
  { value: '个', label: '个' },
  { value: '次', label: '次' },
  { value: '条', label: '条' }
]

const formRef = ref()
const supportTrial = ref('1') // 是否支持试用
const checkAll = ref(false) // 全选
const formState = reactive({
  packageStatus: 1, // 套餐状态
  packageName: '', // 套餐名称
  packageDesc: '', // 套餐介绍
  packageIconKey: '', // 套餐主图key
  packageDetail: '', // 套餐详情
  paymentMethod: 1, // 缴费方式
  packageType: 1, // 套餐类型
  unitPrice: '', // 费用
  unit: '个', //单位
  unitQuantity: '1', //数量
  serviceDays: '', // 服务时间
  tryDays: '' // 试用天数
})

const getFormRules = {
  packageName: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
  packageDesc: [{ required: true, message: '请输入套餐介绍', trigger: 'blur' }],
  packageIconKey: [{ required: true, message: '请上传图片', trigger: 'blur' }],
  packageDetail: [{ required: true, message: '请输入套餐详情', trigger: 'blur' }],
  unitPrice: [{ required: true, message: '请输入费用', trigger: 'blur' }],
  serviceDays: [{ required: true, message: '请输入服务时间', trigger: 'blur' }]
}

const setFormState = (record: any) => {
  formState.packageStatus = record.packageStatus || 1
  formState.packageName = record.packageName || ''
  formState.packageDesc = record.packageDesc || ''
  formState.packageIconKey = record.packageIconKey || ''
  formState.paymentMethod = record.paymentMethod || 1
  formState.packageType = record.packageType || 1
  formState.unitPrice = record.unitPrice || (record.unitPrice === 0 ? 0 : '')
  formState.serviceDays = record.serviceDays || ''
  formState.tryDays = record.tryDays || ''
  formState.packageDetail = record.packageDetail || ''
  formState.unit = record.unit || '个'
  formState.unitQuantity = record.unitQuantity || '1'
}

const [packageRegister, { closeDrawer, changeOkLoading, changeLoading }] = useDrawerInner(async (data) => {
  drawerInfo.type = data.type
  drawerInfo.record = cloneDeep(data.record) || {}
  detailKey.value = detailKey.value + 1
  try {
    changeLoading(true)
    let res = await allGoods()
    changeLoading(false)
    drawerInfo.allGoodsList = res.result || []
    if (drawerInfo.type !== operateActionType.ADD) {
      let detailRes = await packageDetail({ id: drawerInfo.record.id })
      let record = detailRes.result || {}

      // 商品配置名称
      record.goodsNameSetValue = ''
      if (record.goodsNameSet && record.goodsNameSet.length > 0) {
        record.goodsNameSetValue = record.goodsNameSet.join('、')
      }

      drawerInfo.record = cloneDeep(record) || {}
      drawerInfo.originSelectList = cloneDeep(record.goodsCodeSet) || []
      drawerInfo.selectGoodsList = cloneDeep(record.goodsCodeSet) || []
      if (
        drawerInfo.allGoodsList.length === drawerInfo.originSelectList.length &&
        drawerInfo.originSelectList.length > 0
      ) {
        checkAll.value = true
      } else {
        checkAll.value = false
      }
      supportTrial.value = record.tryDays ? '2' : '1'
      setFormState(record)
    }
  } catch (error) {
    changeLoading(false)
  }
})

const drawerReset = () => {
  changeOkLoading(false)
  // setFormState({})
  unref(formRef).resetFields()
  formState.packageDetail = ''
  supportTrial.value = '1'
  drawerInfo.originSelectList = []
  drawerInfo.selectGoodsList = []
  checkAll.value = false
  formState.unitQuantity = '1'
  formState.unit = '个'
}

// 半选节点
const checkIndeterminate = computed(() => {
  return drawerInfo.selectGoodsList.length > 0 && drawerInfo.selectGoodsList.length !== drawerInfo.allGoodsList.length
})

// 缴费方式切换
const paymentMethodChange = (e: Event) => {
  if (formState.paymentMethod == 2 || formState.packageType == 2) {
    formState.tryDays = ''
    supportTrial.value = '1'
  }
}
// 通过商品code获取商品名称
const getShowName = (goodsCode: string) => {
  let index = drawerInfo.allGoodsList.findIndex((item: any) => item.goodsCode === goodsCode)
  let result = index > -1 ? drawerInfo.allGoodsList[index] : {}
  return result.goodsName || ''
}
// 移除选中
const removeSelect = (goodsCode: string) => {
  drawerInfo.selectGoodsList = drawerInfo.selectGoodsList.filter((item: string) => item !== goodsCode)
}
// 点击全选
const onCheckAllChange = (e: any) => {
  if (drawerInfo.selectGoodsList.length === drawerInfo.allGoodsList.length) {
    drawerInfo.selectGoodsList =
      drawerInfo.type === operateActionType.EDIT ? cloneDeep(drawerInfo.originSelectList) : []
    checkAll.value = false
  } else {
    checkAll.value = true
    drawerInfo.selectGoodsList = drawerInfo.allGoodsList.map((item: any) => item.goodsCode)
  }
}
// 点击单个变化
const onCheckChange = (e: any) => {
  checkAll.value =
    drawerInfo.selectGoodsList.length === drawerInfo.allGoodsList.length && drawerInfo.selectGoodsList.length !== 0
}

const previewData = async () => {
  try {
    formState.packageDetail = formState.packageDetail === `<p><br></p>` ? '' : formState.packageDetail
    await unref(formRef).validate()
    if (drawerInfo.selectGoodsList.length === 0) {
      message.error('请选择商品配置')
      return
    } else if (supportTrial.value === '2' && !formState.tryDays) {
      message.error('请输入试用天数')
      return
    }
    PackagePreviewDrawer(true, {
      record: formState
    })
  } catch (error) {
    message.error('信息不完善，无法预览')
  }
}
const authDisabled = (goodsCode: string) => {
  let authBool = false
  if (drawerInfo.type === operateActionType.EDIT) {
    authBool = drawerInfo.originSelectList.includes(goodsCode)
    if (!drawerInfo.record.orderCount) {
      authBool = false
    }
  }
  return authBool
}
// 提交数据
const confirmSubmit = async () => {
  try {
    formState.packageDetail = formState.packageDetail === `<p><br></p>` ? '' : formState.packageDetail
    await unref(formRef).validate()
    if (drawerInfo.selectGoodsList.length === 0) {
      message.error('请选择商品配置')
      return
    } else if (supportTrial.value === '2' && !formState.tryDays) {
      message.error('请输入试用天数')
      return
    }
    changeOkLoading(true)
    if (drawerInfo.type === operateActionType.ADD) {
      await packageAdd({
        ...formState,
        goodsCodeSet: drawerInfo.selectGoodsList
      })
    } else if (drawerInfo.type === operateActionType.EDIT) {
      await packageEdit({
        ...formState,
        goodsCodeSet: drawerInfo.selectGoodsList,
        id: drawerInfo.record.id
      })
    }
    message.success(drawerInfo.type === operateActionType.ADD ? '套餐新增成功' : '套餐编辑成功')
    closeDrawer()
    drawerReset()
    emit('operateSuccess')
  } catch (error) {
    changeOkLoading(false)
  }
}
</script>

<style lang="less" scoped>
.drawer-package {
  padding: 24px 24px 0;
  .package-box {
    padding-bottom: 16px;
    &:last-child {
      padding-bottom: 0;
    }
    .box-form {
      width: 580px;
      margin-top: 28px;
      padding-left: 80px;
      .form-flex {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .form-configuration {
        display: flex;
        justify-content: space-between;
        .configuration-orgin,
        .configuration-select {
          width: 198px;
          background: #ffffff;
          border-radius: 2px;
          border: 1px solid #cdcdcd;
          .box-header {
            height: 44px;
            font-size: 14px;
            padding: 0 8px 0 16px;
            border-bottom: 1px solid #e0e1e6;
            background: #fafafa;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .header-num {
              display: flex;
              align-items: center;
              color: rgba(0, 0, 0, 0.45);
              .num-total {
                margin-left: 8px;
              }
            }
            .header-txt {
              color: #555d6f;
              font-size: 12px;
            }
          }
          :deep(.box-list) {
            height: 256px;
            overflow-y: auto;
            .ant-checkbox-group {
              width: 100%;
              .ant-checkbox-wrapper {
                font-size: 12px;
              }
            }
            .list-item {
              padding: 10px 28px 10px 16px;
              border-bottom: 1px solid #e0e1e6;
              display: flex;
              align-items: center;
              justify-content: space-between;
              position: relative;
              .item-name {
                font-size: 12px;
                color: #192235;
              }
              .item-close {
                position: absolute;
                right: 16px;
                top: 12px;
                color: #c0c0c0;
                margin-left: 8px;
                font-size: 12px;
                flex-shrink: 0;
                cursor: pointer;
              }
            }
            .list-empty {
              text-align: center;
              color: #c0c0c0;
              margin-top: 20px;
            }
          }
        }
      }
    }
    .upload-info {
      color: #c0c0c0;
      font-size: 12px;
      .info-icon {
        font-size: 14px;
        margin-right: 4px;
      }
    }
    .box-detail {
      padding-left: 80px;
      .detail-content {
        width: 820px;
      }
    }
    :deep(.box-desc) {
      margin-top: 40px;
      padding: 0 24px;
      .ant-descriptions-item-label {
        font-size: 12px;
        color: #192236;
        font-weight: 600;
      }
      .ant-descriptions-row > th {
        padding-bottom: 6px;
      }
      .ant-descriptions-row > td {
        padding-bottom: 30px;
      }
    }
  }

  :deep(.ant-form-item-label) {
    font-weight: 600;
    & > label {
      font-size: 12px;
      color: #192236;
    }
  }
  :deep(.unit-price) {
    .ant-form-item-control-input-content {
      display: flex;
      .unit-num {
        width: 128px;
        margin-left: 4px;
        // .ant-input-suffix {
        //   display: none;
        // }
      }
      .ant-select {
        width: 128px;
        margin-left: 4px;
      }
    }
  }
}
</style>
